/**
 * Notes: 门店模块控制器 - 宠物门店预约小程序
 * Date: 2025-01-27 
 */

const BaseController = require('./base_controller.js');
const StoreService = require('../service/store_service.js');
const dataCheck = require('../../framework/validate/data_check.js');
const timeUtil = require('../../framework/utils/time_util.js');
const UserModel = require('../model/user_model.js');
const PassportService = require('../service/passport_service.js');
const config = require('../../config/config.js');

class StoreController extends BaseController {

	constructor(route, openId, event) {
		// 门店相关接口允许匿名访问，为空时使用默认值
		const effectiveOpenId = openId || 'anonymous_user';
		super(route, effectiveOpenId, event);
		
		// 保存真实的用户ID（可能为空）
		this._realUserId = openId;
		this._userId = openId || null;
		this._token = event.token || event.params?.token || '';
		this._timestamp = timeUtil.time();
	}

	/**
	 * 数据校验
	 * @param {*} rules 
	 */
	validateData(rules = {}) {
		let input = this._request;
		return dataCheck.check(input, rules);
	}

	/**
	 * 获取门店列表
	 */
	async getStoreList() {
		// 数据校验
		let rules = {
			longitude: 'must|number|name=经度',
			latitude: 'must|number|name=纬度',
			radius: 'number|min:1|max:50|name=搜索半径',
		};

		let input = this.validateData(rules);

		let service = new StoreService();
		return await service.getStoreList(input.longitude, input.latitude, input.radius || 10);
	}

	/**
	 * 获取门店详情
	 */
	async getStoreDetail() {
		// 数据校验
		let rules = {
			storeId: 'must|string|min:1|max:50|name=门店ID',
		};

		let input = this.validateData(rules);

		let service = new StoreService();
		return await service.getStoreDetail(input.storeId);
	}

	/**
	 * 获取门店服务列表
	 */
	async getStoreServices() {
		// 数据校验
		let rules = {
			storeId: 'must|string|min:1|max:50|name=门店ID',
			serviceType: 'string|min:1|max:20|name=服务类型',
		};

		let input = this.validateData(rules);

		let service = new StoreService();
		return await service.getStoreServices(input.storeId, input.serviceType);
	}

	/**
	 * 获取门店寄养房间列表
	 */
	async getStoreFosterRooms() {
		// 数据校验
		let rules = {
			storeId: 'must|string|min:1|max:50|name=门店ID',
		};

		let input = this.validateData(rules);

		let service = new StoreService();
		return await service.getStoreFosterRooms(input.storeId);
	}

	/**
	 * 添加门店
	 */
	async addStore() {
		this.ensureAuthenticatedForWrite();
		// 数据校验
		let rules = {
			name: 'must|string|min:1|max:50|name=门店名称',
			address: 'string|max:200|name=地址',
			phone: 'string|max:20|name=电话',
			avatar: 'string|max:200|name=封面',
			desc: 'string|max:500|name=简介'
		};

		let input = this.validateData(rules);

		// TEST_MODE 下直接返回模拟数据，避免访问云数据库
		if (config.TEST_MODE) {
			return {
				_id: 'store_test_' + Date.now(),
				userId: this._userId || 'anonymous_user',
				name: input.name,
				address: input.address || '',
				phone: input.phone || '',
				avatar: input.avatar || '',
				desc: input.desc || '',
				createTime: this._timestamp,
				updateTime: this._timestamp
			};
		}

		// 用户存在性预检与自动建档兜底（非测试模式）
		let user = await UserModel.getOne({ _id: this._userId });
		if (!user) {
			const passport = new PassportService();
			await passport.registerUser(this._userId, {});
		}

		let service = new StoreService();
		return await service.addStore(this._userId, input);
	}

	/**
	 * 更新门店信息
	 */
	async updateStore() {
		this.ensureAuthenticatedForWrite();
		// 数据校验
		let rules = {
			storeId: 'must|string|min:1|max:50|name=门店ID',
			name: 'string|min:1|max:50|name=门店名称',
			address: 'string|max:200|name=地址',
			phone: 'string|max:20|name=电话',
			avatar: 'string|max:200|name=封面',
			desc: 'string|max:500|name=简介'
		};

		let input = this.validateData(rules);

		// TEST_MODE 下直接返回模拟数据，避免访问云数据库
		if (config.TEST_MODE) {
			return {
				_id: input.storeId,
				userId: this._userId,
				name: input.name,
				address: input.address,
				phone: input.phone,
				avatar: input.avatar,
				desc: input.desc,
				updateTime: this._timestamp
			};
		}

		// 用户存在性预检与自动建档兜底（非测试模式）
		let user = await UserModel.getOne({ _id: this._userId });
		if (!user) {
			const passport = new PassportService();
			await passport.registerUser(this._userId, {});
		}

		let service = new StoreService();
		return await service.updateStore(input.storeId, this._userId, input);
	}
}

module.exports = StoreController;
